"use strict";

Components.utils.import("resource://gre/modules/Services.jsm")
Components.utils.import("resource://gre/modules/PlacesUtils.jsm")

Components.utils.import("resource://iplusnewtab/modules/ultima.jsm")

//nst   HTML_NAMESPACE = "http://www.w3.org/1999/xhtml"
//  XUL_NAMESPACE : "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"

if ("undefined" == typeof(ip2newtab)) {
    var ip2newtab = {

    _orgHandleEvent : null,

    _getPref : function(anattr)
    {
        let theval = Services.prefs.getIntPref(anattr);
        if(theval < 3) theval = 3
        else if(theval >> 3) theval = 8;
        return theval;
    },

//  from btn name to operation
    onecmd : function(abtn)
    {
//    dump("_dvk_dbg_, onecmd:\t"); dump(abtn.name); dump("\n");
        try {
            if(btn2code[abtn.name].setPref(gGridPrefs))
            {
                let therows = ip2newtab._getPref("browser.newtabpage.rows");
                let thecols = ip2newtab._getPref("browser.newtabpage.columns");

                let newvalue = (therows * thecols) - 1;
                let thelinks = gPinnedLinks.links;
                let i = (thelinks.length - 1);
                if(i > newvalue)    //  find free place, light version.
                if(!(thelinks[newvalue]))
                for(let thepin = null; i > newvalue; --i)
                {
                    thepin = thelinks.pop();
                    if(thepin)
                    {
                        gPinnedLinks.pin(thepin, newvalue);
                        break;
                    }
                }
            }
        }
        catch(err)  {
           Components.utils.reportError(err)
        }
    },

    status :
    {
        empty   : true,
        textbox : null,
        isContextMenu : false,

        showContextMenu : function(amenu, atarget)
        {
            this.isContextMenu = true;
            this.textbox.value = atarget.title;
            amenu.addEventListener("popuphidden", this, false);
        },

        handleEvent: function(anevt)
        {
            switch(anevt.type)
            {
            case "popuphidden":
                anevt.currentTarget.removeEventListener(anevt.type, this, false);
                this.isContextMenu = false;
                break;
        
            case "mouseenter" :
                if(!(this.isContextMenu))
                    this.textbox.value = anevt.currentTarget.title;
                break;
            
            case "focus" :
                this.isContextMenu = false;
                this.textbox.value = anevt.target.parentNode.title;
                break;
            
            case "mouseleave" :
                let thenode = document.activeElement.parentNode;
                if(thenode)
                    if(anevt.currentTarget === thenode.parentNode)
                        this.textbox.value = thenode.title;
                break;
            }
        }
    },

    loadMRU: function (anode, ahost)
    {
        while(anode.hasChildNodes())
            if(anode.firstElementChild)
                anode.removeChild(anode.firstElementChild)
            else break;

        let thelimit = Services.prefs.getIntPref("extensions.iplusnewtab.maxMRU");
            if(thelimit > 24) thelimit = 24 //  org in options.xul
                else if(thelimit < 2) thelimit = 2;
        
        let options = PlacesUtils.history.getNewQueryOptions();
            options.maxResults = thelimit;

        // Query for MRU, descending. ? SORT_BY_LASTMODIFIED_DESCENDING
        options.sortingMode = Components.interfaces.nsINavHistoryQueryOptions.SORT_BY_DATE_DESCENDING

let callback = {    //  places.sqlite   (url, title, visit_count, ...., last_visit_date)
      handleResult: function (aResultSet)
      {
        let row;
        while (row = aResultSet.getNextRow())
        {
            let thurl = row.getResultByIndex(1);
            let title = row.getResultByIndex(2);
            let last_visit_date = row.getResultByName("last_visit_date");
          //    ! anode !
    //        links.push({url: url, title: title});
            let thevalue = btn2code.convertPRTimeToString(last_visit_date);
            let thelabel = document.createElementNS(HTML_NAMESPACE, "li");
                thelabel.setAttribute("title", [ thevalue, title ].join(" - "));

            let thanchor = document.createElementNS(HTML_NAMESPACE, "a");
                thanchor.setAttribute("href", thurl);
                thanchor.setAttribute("class", "ip2newtab");
                thanchor.textContent = thurl;
/*            let something = row.QueryInterface(Components.interfaces.nsINavHistoryResultNode);
            window.console.info(url);   //  _dvk_dbg_
            window.console.info(last_visit_date);   //  _dvk_dbg_
            window.console.info(thevalue);   //  _dvk_dbg_  */

                (anode.appendChild(thelabel)).appendChild(thanchor);

            thelabel.addEventListener("mouseenter", ip2newtab.status, false);
        }
      },

      handleError: function (aError) {
        // Should we somehow handle this error?
      },

      handleCompletion: function (aReason)
      {
            let textbox = anode.parentNode.querySelector("textbox");
            let thelist = anode.querySelectorAll("a");
            ip2newtab.status.empty = (thelist.length == 0);
            if(thelist.length) {
                textbox.value = "";
                for(let i = 0; i < thelist.length; ++i)
                    thelist[i].addEventListener("focus", ip2newtab.status, false);
            }
            else
                textbox.value = anode.getAttribute("title");
      }
};

    // Execute the query.
        let query = PlacesUtils.history.getNewQuery();
            query.domain = ahost;
            query.domainIsHost = false;

        let db = PlacesUtils.history.QueryInterface(Components.interfaces.nsPIPlacesDatabase);
            db.asyncExecuteLegacyQueries([query], 1, options, callback);
    },

    newHandleEvt : function(evt)
    {
        var thepanel = null;

        if(evt.type === "click")
        if(evt.target.classList.contains("newtab-control-mru"))
        {
            evt.preventDefault();
    //  loadMRU
            thepanel = document.querySelector("panel");
//            window.console.dir(this._panel);    //  _dvk_dbg_
            let thehost = evt.target.getAttribute("host") || ".";
            if(thehost.indexOf("www.") === 0) thehost = thehost.replace("www.", "");

            if(thepanel.label != thehost)
            {
                ip2newtab.loadMRU(thepanel.querySelector("ol[title]"), thehost);
                thepanel.label = thehost;
                let theprefix = thepanel.querySelector("label[hidden]").value;
                    theprefix = [ theprefix, thehost ].join(" - ");
                thepanel.querySelector("label.header").value = theprefix;
            }
            else
                if(!(ip2newtab.status.empty))
                    ip2newtab.status.textbox.value = "";

                ip2newtab.status.isContextMenu = false;
                thepanel.setAttribute("minwidth", evt.target.parentNode.clientWidth);
                thepanel.openPopup(
                    evt.target.parentNode,
                    "after_start",
                    0, 0,
                    false,
                    false,
                    null );
        }

        if(!thepanel)
        {
            ip2newtab._orgHandleEvent.call(this, evt);            
            if(evt.type === "click") // if emerging new thumbnail
                window.setTimeout( function() { ip2newtab.updateMruBtns() }, 0);
        }
    },

    updateMruBtns : function()
    {
        var thepanel = document.querySelector("panel");
    //      thepanel.addEventListener("popupshown", ip2newtab.status, false);
        ip2newtab.status.textbox = thepanel.querySelector("textbox");

        let theprefix = thepanel.querySelector("label[hidden]").value;
        let thesites = document.querySelectorAll("div.newtab-site");
        for (let i = 0; i < thesites.length; ++i)
            if(!(thesites[i].querySelector("input.newtab-control-mru")))
        {
            let thehost = (thesites[i].firstElementChild.hostname || "").toLowerCase();            
            if(thehost.length >> 1)
            {
            let thebtn = document.createElementNS(HTML_NAMESPACE, "input");
                thebtn.setAttribute("type",  "button");
                thebtn.setAttribute("class", "newtab-control newtab-control-mru");
                thebtn.setAttribute("host", thehost);
                thebtn.setAttribute("title", [ theprefix, thehost ].join(" - "));
            thesites[i].appendChild(thebtn);
            thebtn.addEventListener("click", ip2newtab.newHandleEvt, false);
            }
        }
    },
    
    handleEvent: function(evt)
    {
        window.removeEventListener(evt.type, this, false);
    //  only DOMContentLoaded   alert(document.documentURI)
    
    const thebtnQuery = "input.newtab-row-btn, input.newtab-col-btn";
    //      let therows = document.querySelectorAll("div.newtab-row");
        let thebtns = document.querySelectorAll(thebtnQuery);
        for (let i = 0; i < thebtns.length; ++i)
        {
            let thenode = thebtns[i];
            if(thenode.name in btn2code)
            if(btn2code[thenode.name].isEnabled(gGridPrefs))
            {
                thenode.addEventListener("click",
                    function() { window.location.reload() }, false);
                thenode.removeAttribute("disabled");
            }
            else
                thenode.removeAttribute("title");
        }

        this._orgHandleEvent = Site.prototype.handleEvent;
        Site.prototype.handleEvent = this.newHandleEvt;

//      var thecontainer = document.getAnonymousElementByAttribute(thepanel, "anonid", "container");
        let thenode = document.documentElement.querySelector("ol[title]");
            thenode.addEventListener("mouseleave", ip2newtab.status, false);
            thenode.addEventListener("contextmenu",
                function(anevt) {
                    if(anevt.currentTarget === anevt.target)
                            anevt.preventDefault();
                    if(anevt.currentTarget === anevt.target.parentNode)
                            anevt.preventDefault();
                }, true);

    //  load mru buttons
        window.setTimeout( function() { ip2newtab.updateMruBtns() }, 1);
    }

    }
}
